package com.commerce.reader.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;


import com.bumptech.glide.Glide;
import com.commerce.reader.Activity.DescActivity;
import com.commerce.reader.Entity.Book;
import com.commerce.reader.Entity.Books;
import com.commerce.reader.R;

import java.io.Serializable;


public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textName = root.findViewById(R.id.fh_tv_name);
        final TextView textTime= root.findViewById(R.id.fh_tv_time);
        final TextView textDesc = root.findViewById(R.id.fh_tv_desc);
        final ImageView imgBook = root.findViewById(R.id.fh_tv_img);
        final LinearLayout toBook = root.findViewById(R.id.fh_ll_toBooks);
        homeViewModel.getBook().observe(getViewLifecycleOwner(), new Observer<Book>() {
            @Override
            public void onChanged(Book books) {
                Glide.with(getActivity()).load(books.getImgurl()).into(imgBook);
                textName.setText(books.getBook());
                textTime.setText(books.getName()+"\n"+books.getTime());
                textDesc.setText(books.getDesc());
            }
        });
        toBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Books books = homeViewModel.randomBooks();
                if(books!=null){
                    Intent intent = new Intent(getActivity(), DescActivity.class);
                    intent.putExtra("books", (Serializable) books);
                    startActivity(intent);
                }

            }
        });
        return root;
    }
}